package com.weizhu.swufer.core.client;

import com.weizhu.swufer.core.annotation.SwuferLimit;
import com.weizhu.swufer.core.cluster.Cluster;
import com.weizhu.swufer.core.entity.InvokeParam;
import com.weizhu.swufer.core.filter.FilterChain;
import com.weizhu.swufer.core.filter.FilterManager;
import com.weizhu.swufer.core.filter.LimitFilter;
import com.weizhu.swufer.core.loadbalance.LoadBalancer;
import com.weizhu.swufer.core.rpc.RpcContext;
import com.weizhu.swufer.core.rpc.RpcEngine;
import com.weizhu.swufer.core.rpc.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Rpc调用代理类
 */
public class ReferenceProxyHandler implements InvocationHandler {

    private ReferenceConfig referenceConfig;

    private Invoker invoker;


    public ReferenceProxyHandler(ReferenceConfig config){
        this.referenceConfig = config;
        invoker = Cluster.getClusterInvoker(referenceConfig);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        InvokeParam invokeParam = new InvokeParam();
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setInterfaceName(referenceConfig.getReferServiceName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setArgs(args);
        rpcRequest.setArgTypes(method.getParameterTypes());
        rpcRequest.setMaxWaitTime(referenceConfig.getMaxWaitTime());

        invokeParam.setRpcRequest(rpcRequest);
        invokeParam.setTargetAddress(referenceConfig.getTargetAddress());
        invokeParam.setAsync(referenceConfig.isAsync());
        invokeParam.setTryTimes(referenceConfig.getTryTimes());
        return invoker.invoke(invokeParam);
    }
}
